/**
 * 构建应用菜单
 * 使用模块化的菜单配置和构建器
 * @param {Object} options - 菜单选项
 * @param {boolean} options.secondary - 是否为次要菜单（右键菜单）
 * @returns {Menu} Electron Menu 对象
 */
function buildAppMenu (options = {}) {
  const keyMap = userKeyMap(settings.get('keyMap'))

  /**
   * 获取格式化的快捷键映射
   * @param {string} keybinding - 快捷键绑定键
   * @returns {string|null} 格式化的快捷键字符串
   */
  function getFormattedKeyMapEntry (keybinding) {
    const value = keyMap[keybinding]

    if (value) {
      if (Array.isArray(value)) {
        // value is array if multiple entries are set
        return value[0].replace('mod', 'CmdOrCtrl')
      } else {
        return value.replace('mod', 'CmdOrCtrl')
      }
    }

    return null
  }

  // 创建菜单配置
  const menuConfig = createMenuConfig(getFormattedKeyMapEntry, {
    sendIPCToWindow,
    createWindow,
    showFocusModeDialog1,
    showFocusModeDialog2,
    openTabInWindow,
    isFocusMode,
    windows,
    settings,
    app,
    webContents,
    getWindowWebContents,
    destroyAllViews,
    placesWindow,
    electron,
    isDevelopmentMode,
    isDebuggingEnabled,
    isHarmonyOSPlatform
  })

  // 创建菜单构建器
  const builder = new MenuBuilder(menuConfig, options)

  // 构建并返回菜单
  return builder.build()
}

/**
 * 创建 Dock 菜单（仅 macOS）
 * 基于 Electron 文档示例：https://github.com/electron/electron/blob/master/docs/tutorial/desktop-environment-integration.md#custom-dock-menu-macos
 */
function createDockMenu () {
  if (process.platform !== 'darwin') {
    return
  }

  const keyMap = userKeyMap(settings.get('keyMap'))

  function getFormattedKeyMapEntry (keybinding) {
    const value = keyMap[keybinding]
    if (value) {
      if (Array.isArray(value)) {
        return value[0].replace('mod', 'CmdOrCtrl')
      } else {
        return value.replace('mod', 'CmdOrCtrl')
      }
    }
    return null
  }

  // 创建菜单配置
  const menuConfig = createMenuConfig(getFormattedKeyMapEntry, {
    sendIPCToWindow,
    createWindow,
    showFocusModeDialog1,
    showFocusModeDialog2,
    openTabInWindow,
    isFocusMode,
    windows,
    settings,
    app,
    webContents,
    getWindowWebContents,
    destroyAllViews,
    placesWindow,
    electron,
    isDevelopmentMode,
    isDebuggingEnabled,
    isHarmonyOSPlatform
  })

  // 创建菜单构建器并构建 Dock 菜单
  const builder = new MenuBuilder(menuConfig, {})
  const dockMenu = builder.buildDockMenu()

  if (dockMenu) {
    app.dock.setMenu(dockMenu)
  }
}
